package com.ruoyi.framework.web.service;

import com.ruoyi.system.domain.ZnTenant;
import com.ruoyi.system.mapper.ZnTenantMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.service.ISysUserService;

import java.util.Date;
import java.util.HashMap;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPermissionService permissionService;
    @Autowired
    private ZnTenantMapper znTenantMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        SysUser user = userService.selectUserByUserName(username);
        if (StringUtils.isNull(user))
        {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException("登录用户：" + username + " 不存在");
        }
        else if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        }
        else if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }else if (UserStatus.EXPIRE.getCode().equals(user.getStatus()))
        {
            log.info("登录用户：{} 已到期.", username);
            throw new ServiceException("对不起，您的账号：" + username + " 已到期");
        }
        if("01".equals(user.getUserType())){
            ZnTenant znTenant=znTenantMapper.selectZnTenantByTenant(user.getTenantId());
            if(znTenant==null){
                log.info("登录租户：{} 已被清除.", username);
                throw new ServiceException("对不起，您的账号：" + username + " 已被清除");
            }else{
                if(znTenant.getExpireTime()!=null){
                   Date now = new Date();
                   if(znTenant.getExpireTime().before(now) || UserStatus.EXPIRE.getCode().equals(znTenant.getEnabled())){
                       log.info("登录租户：{} 已到期.", username);
                       throw new ServiceException("对不起，您的账号：" + username + " 已到期，请联系管理员");
                   }
                }
            }
        }

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user)
    {
        return new LoginUser(user.getUserId(), user.getDeptId(), user, permissionService.getMenuPermission(user));
    }

    /**
     * 新的身份认证方法
     * @param username
     * @param details  map集合 ：companyName （公司名称）：userType （密码）
     * @return
     */
    public UserDetails loadUserByUsername(String username, Object details) {
        String userType = ((HashMap)details).get("userType").toString();
        SysUser user = null;
        if(userType.equals("01")){//管理员
            user = userService.selectUserByUserName(username);
        }else if(userType.equals("02")){//普通用户
            user = userService.selectUserByUserNameAndCompanyName(username,((HashMap)details).get("companyName").toString());
        }

        if (StringUtils.isNull(user))
        {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException("登录用户：" + username + " 不存在");
        }
        else if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        }
        else if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }else if (UserStatus.EXPIRE.getCode().equals(user.getStatus()))
        {
            log.info("登录用户：{} 已到期.", username);
            throw new ServiceException("对不起，您的账号：" + username + " 已到期");
        }
        if("01".equals(user.getUserType())){
            ZnTenant znTenant=znTenantMapper.selectZnTenantByTenant(user.getTenantId());
            if(znTenant==null){
                log.info("登录租户：{} 已被清除.", username);
                throw new ServiceException("对不起，您的账号：" + username + " 已被清除");
            }else{
                if(znTenant.getExpireTime()!=null){
                    Date now = new Date();
                    if(znTenant.getExpireTime().before(now) || UserStatus.EXPIRE.getCode().equals(znTenant.getEnabled())){
                        log.info("登录租户：{} 已到期.", username);
                        throw new ServiceException("对不起，您的账号：" + username + " 已到期，请联系管理员");
                    }
                }
            }
        }

        return createLoginUser(user);
    }
}
